import { message } from 'antd';
// 基础请求配置
const baseConfig = {
  baseUrl: 'http://localhost:3366', // 替换为你的 API 基础 URL
  timeout: 5000, // 请求超时时间，单位：毫秒
};

// 请求配置类型
interface RequestOptions {
  method?: string;
  headers?: Record<string, string>;
  body?: string;
}
// 通用响应结构
interface ApiResponse<T> {
  code: number;
  msg: string;
  data: T;
}

// 封装 fetch 请求
const request = async <T>(
  url: string,
  options: RequestOptions = {},
): Promise<ApiResponse<T> | null> => {
  // 合并请求配置
  const config: RequestOptions = {
    ...options,
    method: options.method || 'GET',
    headers: {
      'Content-Type': 'application/json',
      ...options.headers,
    },
  };
  // 拼接完整的请求 URL
  const fullUrl = `${baseConfig.baseUrl}${url}`;

  try {
    // 创建 AbortController 用于处理请求超时
    const controller = new AbortController();
    const id = setTimeout(() => controller.abort(), baseConfig.timeout);

    // 发送请求
    const response = await fetch(fullUrl, {
      ...config,
      signal: controller.signal,
    });

    // 清除超时定时器
    clearTimeout(id);
    // 解析响应数据并进行类型断言
    const data = await response.json() as ApiResponse<T>;
    // 检查响应状态码
    if (!response.ok) {
      if (data.code !== 0) {
        message.error(data.msg);
      }
      throw new Error(`请求失败，状态码：${response.status}`);
    }
    // 返回解析后的数据
    return data;
  } catch (error) {
    if (error instanceof Error && error.name === 'AbortError') {
      console.error('请求超时，请稍后重试');
    } else {
      console.error(
        '请求发生错误：',
        error instanceof Error ? error.message : String(error),
      );
    }
    return null;
  }
};

// 封装 GET 请求
const get = <T>(
  url: string,
  params: Record<string, any> = {},
  options: RequestOptions = {},
): Promise<ApiResponse<T> | null> => {
  if (params.pageSize) {
    params.limit = params.pageSize;
    delete params.pageSize;
  }
  if (params.current) {
    params.page = params.current;
    delete params.current;
  }

  // 拼接查询参数
  const queryParams = new URLSearchParams(params).toString();
  const fullUrl = queryParams ? `${url}?${queryParams}` : url;

  return request<T>(fullUrl, {
    ...options,
    method: 'GET',
  });
};

// 封装 POST 请求
const post = <T>(
  url: string,
  data: Record<string, any> = {},
  options: RequestOptions = {},
): Promise<ApiResponse<T> | null> => {
  return request<T>(url, {
    ...options,
    method: 'POST',
    body: JSON.stringify(data),
  });
};

// 封装 PUT 请求
const put = <T>(
  url: string,
  data: Record<string, any> = {},
  options: RequestOptions = {},
): Promise<ApiResponse<T> | null> => {
  return request<T>(url, {
    ...options,
    method: 'PUT',
    body: JSON.stringify(data),
  });
};

// 封装 DELETE 请求
const del = <T>(
  url: string,
  options: RequestOptions = {},
): Promise<ApiResponse<T> | null> => {
  return request<T>(url, {
    ...options,
    method: 'DELETE',
  });
};

export { del, get, post, put };